package com.simpleim.starter.client;

import com.simpleim.codec.SimpleProtobufDecoder;
import com.simpleim.codec.SimpleProtobufEncoder;
import com.simpleim.starter.handler.ExceptionHandler;
import com.simpleim.starter.handler.LoginResponseHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.net.InetSocketAddress;

@Service
public class ChatNettyClient {

    private static final Logger LOGGER = LoggerFactory.getLogger(ChatNettyClient.class);

    private Bootstrap bootstrap;

    @Value("${server.ip}")
    private String host;

    @Value("${server.port}")
    private String port;

    private ChannelFutureListener listener;

    private EventLoopGroup loopGroup;

    /**
     * 连接服务端
     */
    public void doConnect() {
        bootstrap = new Bootstrap();

        loopGroup = new NioEventLoopGroup();
        bootstrap.group(loopGroup);
        bootstrap.channel(NioSocketChannel.class);

        bootstrap.option(ChannelOption.SO_KEEPALIVE, true);

        try {
            bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new SimpleProtobufDecoder());
                    ch.pipeline().addLast(new SimpleProtobufEncoder());
                    ch.pipeline().addLast("login", new LoginResponseHandler());
                    ch.pipeline().addLast(new ExceptionHandler());
                }
            });
            LOGGER.info("开始连接服务端：{}", host);
            ChannelFuture connect = bootstrap.connect(new InetSocketAddress(host, Integer.parseInt(port)));
            connect.addListener(listener);
        } catch (Exception e) {
            LOGGER.error("服务端：{}连接失败", host);
        }
    }

    public void close() {
        loopGroup.shutdownGracefully();
    }

    public void setListener(ChannelFutureListener listener) {
        this.listener = listener;
    }
}
